package com.koron.order.linepatrol.check.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.BaseBean;
import com.koron.bean.query.PageQuery;
import com.koron.common.core.util.CodeTools;
import com.koron.common.core.util.StringUtils;
import com.koron.order.linepatrol.check.bean.dto.LinePatrolCheckSatelliteDTO;
import com.koron.order.linepatrol.check.bean.po.LinePatrolCheckSatellite;
import com.koron.order.linepatrol.check.bean.query.LinePatrolCheckSatelliteQuery;
import com.koron.order.linepatrol.check.bean.vo.LinePatrolCheckSatelliteVO;
import com.koron.order.linepatrol.check.convertor.LinePatrolCheckSatelliteConvertor;
import com.koron.order.linepatrol.check.mapper.LinePatrolCheckSatelliteMapper;
import com.koron.order.linepatrol.check.service.LinePatrolCheckSatelliteService;
import com.koron.order.linepatrol.satellite.bean.po.LinePatrolMonitorChange;
import com.koron.order.linepatrol.satellite.bean.po.LinePatrolSatellite;
import com.koron.order.linepatrol.satellite.service.LinePatrolMonitorChangeService;
import com.koron.order.linepatrol.satellite.service.LinePatrolSatelliteService;
import com.koron.order.linepatrol.uav.bean.VO.LineRiskPatrolUnvDetail;
import com.koron.order.linepatrol.uav.service.LineRiskPatrolUnvDetailService;
import com.koron.order.risk.base.bean.po.LineStaff;
import com.koron.order.risk.base.service.LineStaffService;
import com.koron.order.risk.feign.LineEquipmentFeign;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 卫星巡视风险核实工单(LinePatrolCheckSatellite)表服务实现类
 *
 * @author jzp
 * @since 2023-02-08 10:25:50
 */
@Service
public class LinePatrolCheckSatelliteServiceImpl implements LinePatrolCheckSatelliteService {

    final String staffType = "卫星巡视风险核实工单-核实人员";
    @Autowired
    private LineStaffService lineStaffService;

    @Autowired
    private LinePatrolCheckSatelliteConvertor linePatrolCheckSatelliteConvertor;
    @Autowired
    private LinePatrolMonitorChangeService linePatrolMonitorChangeService;
    @Autowired
    private LinePatrolSatelliteService linePatrolSatelliteService;
    @Autowired
    private LineRiskPatrolUnvDetailService lineRiskPatrolUnvDetailService;
    @Autowired
    LineEquipmentFeign lineEquipmentFeign;
    /**
     * 通过ID查询单条数据
     *
     */
    @Override
    @TaskAnnotation("getById")
    public LinePatrolCheckSatellite getById(SessionFactory factory, String id) {
        LinePatrolCheckSatelliteMapper mapper = factory.getMapper(LinePatrolCheckSatelliteMapper.class);
        return mapper.selectById(id);
    }

    @Override
    @TaskAnnotation("getVoById")
    public LinePatrolCheckSatelliteVO getVoById(SessionFactory factory, String id) {
        LinePatrolCheckSatellite linePatrolCheckSatellite = getById(factory, id);
        LinePatrolCheckSatelliteVO linePatrolCheckSatelliteVO = linePatrolCheckSatelliteConvertor.entityToVo(linePatrolCheckSatellite);
        // 查询值守人员
        List<LineStaff> lineStaffs = lineStaffService.listByOrderId(factory, id);
        linePatrolCheckSatelliteVO.setCheckStaffs(lineStaffs);
        return linePatrolCheckSatelliteVO;
    }

    @Override
    @TaskAnnotation("getDtoById")
    public LinePatrolCheckSatelliteDTO getDtoById(SessionFactory factory, String id) {
        LinePatrolCheckSatelliteVO linePatrolCheckSatelliteVO = getVoById(factory, id);
        LinePatrolCheckSatelliteDTO linePatrolCheckSatelliteDTO = linePatrolCheckSatelliteConvertor.voToDto(linePatrolCheckSatelliteVO);
        List towerIds = new ArrayList();
        if (satellite.equals(linePatrolCheckSatelliteDTO.getDataSource())) {
            linePatrolCheckSatelliteDTO.setLinePatrolSatelliteList(linePatrolSatelliteService.listByCheckId(factory, id));
           List<LinePatrolSatellite> linePatrolSatelliteList = linePatrolCheckSatelliteDTO.getLinePatrolSatelliteList();
            if (!CollectionUtils.isEmpty(linePatrolSatelliteList)){

                linePatrolSatelliteList.stream().forEach(linePatrolSatellite-> {
                    if (StringUtils.isNotEmpty(linePatrolSatellite.getTowerId())){
                        towerIds.add(linePatrolSatellite.getTowerId());
                    }
                });
                Map<String, Map<String, String>> paramsMap = (Map<String, Map<String, String>>) lineEquipmentFeign.getTowerParams(towerIds).getData();
                // 拿到该设备的经纬度
                for (LinePatrolSatellite linePatrolSatellite: linePatrolSatelliteList) {
                    Map<String, String> map = paramsMap.get(linePatrolSatellite.getTowerId());
                    String longitude = map.getOrDefault("longitude", null);
                    String latitude = map.getOrDefault("latitude", null);
                    linePatrolSatellite.setLongitude(longitude);
                    linePatrolSatellite.setLatitude(latitude);
                }}
        } else if (monitorChange.equals(linePatrolCheckSatelliteDTO.getDataSource())) {
            linePatrolCheckSatelliteDTO.setLinePatrolMonitorChangeList(linePatrolMonitorChangeService.listByCheckId(factory, id));
                List<LinePatrolMonitorChange>  linePatrolMonitorChangeList = linePatrolCheckSatelliteDTO.getLinePatrolMonitorChangeList();
                if (!CollectionUtils.isEmpty(linePatrolMonitorChangeList)){
                    linePatrolMonitorChangeList.stream().forEach(linePatrolMonitorChange-> {
                        if (StringUtils.isNotEmpty(linePatrolMonitorChange.getTowerId())){
                            towerIds.add(linePatrolMonitorChange.getTowerId());
                        }
                    });
                    Map<String, Map<String, String>> paramsMap = (Map<String, Map<String, String>>) lineEquipmentFeign.getTowerParams(towerIds).getData();
                    // 拿到该设备的经纬度
                    for (LinePatrolMonitorChange linePatrolMonitorChange: linePatrolMonitorChangeList) {
                        Map<String, String> map = paramsMap.get(linePatrolMonitorChange.getTowerId());
                        String longitude = map.getOrDefault("longitude", null);
                        String latitude = map.getOrDefault("latitude", null);
                        linePatrolMonitorChange.setLongitude(longitude);
                        linePatrolMonitorChange.setLatitude(latitude);
                    }}
        } else if (uavRisk.equals(linePatrolCheckSatelliteDTO.getDataSource())) {
            linePatrolCheckSatelliteDTO.setLineRiskPatrolUnvDetailList(lineRiskPatrolUnvDetailService.listByCheckId(factory, id));
                   List<LineRiskPatrolUnvDetail> lineRiskPatrolUnvDetailList = linePatrolCheckSatelliteDTO.getLineRiskPatrolUnvDetailList();
                    if (!CollectionUtils.isEmpty(lineRiskPatrolUnvDetailList)){
                        lineRiskPatrolUnvDetailList.stream().forEach(lineRiskPatrolUnvDetail-> {
                            if (StringUtils.isNotEmpty(lineRiskPatrolUnvDetail.getTowerId())){
                                towerIds.add(lineRiskPatrolUnvDetail.getTowerId());
                            }
                        });
                        Map<String, Map<String, String>> paramsMap = (Map<String, Map<String, String>>) lineEquipmentFeign.getTowerParams(towerIds).getData();
                        // 拿到该设备的经纬度
                        for (LineRiskPatrolUnvDetail lineRiskPatrolUnvDetail: lineRiskPatrolUnvDetailList) {
                            Map<String, String> map = paramsMap.get(lineRiskPatrolUnvDetail.getTowerId());
                            String longitude = map.getOrDefault("longitude", null);
                            String latitude = map.getOrDefault("latitude", null);
                            lineRiskPatrolUnvDetail.setLongitude(longitude);
                            lineRiskPatrolUnvDetail.setLatitude(latitude);
                        }
        }}
        return linePatrolCheckSatelliteDTO;
    }

    /**
     * 查询所有数据
     *
     */
    @Override
    @TaskAnnotation("list")
    public List<LinePatrolCheckSatellite> list(SessionFactory factory, LinePatrolCheckSatelliteQuery query) {
        LinePatrolCheckSatelliteMapper mapper = factory.getMapper(LinePatrolCheckSatelliteMapper.class);
        return mapper.selectList(query);
    }

    @Override
    @TaskAnnotation("listVo")
    public List<LinePatrolCheckSatelliteVO> listVo(SessionFactory factory, LinePatrolCheckSatelliteQuery query) {
        LinePatrolCheckSatelliteMapper mapper = factory.getMapper(LinePatrolCheckSatelliteMapper.class);
        List<LinePatrolCheckSatelliteVO> linePatrolCheckSatelliteVOList = null;
        if (satellite.equals(query.getDataSource())) {
            linePatrolCheckSatelliteVOList = mapper.selectSatelliteList(query);
        } else if (monitorChange.equals(query.getDataSource())) {
            linePatrolCheckSatelliteVOList = mapper.selectMonitorChangeList(query);
        } else if (uavRisk.equals(query.getDataSource())) {
            linePatrolCheckSatelliteVOList = mapper.selectUavRiskList(query);
        }

        if (CollUtil.isEmpty(linePatrolCheckSatelliteVOList)) {
            return Collections.emptyList();
        }
        List<String> ids = linePatrolCheckSatelliteVOList.stream().map(BaseBean::getId).collect(Collectors.toList());
        // 查询人员
        List<LineStaff> lineStaffs = lineStaffService.listByOrderIds(factory, ids);

        if (CollUtil.isNotEmpty(lineStaffs)) {
            Map<String, List<LineStaff>> collect = lineStaffs.stream().collect(Collectors.groupingBy(LineStaff::getOrderId));
            linePatrolCheckSatelliteVOList.forEach(e -> e.setCheckStaffs(collect.get(e.getId())));
        }
        return linePatrolCheckSatelliteVOList;
    }

    @Override
    @TaskAnnotation("page")
    public PageInfo<LinePatrolCheckSatelliteVO> page(SessionFactory factory, PageQuery pageQuery, LinePatrolCheckSatelliteQuery query) {
        return LinePatrolCheckSatelliteService.super.page(factory, pageQuery, query);
    }

    /**
     * 新增数据
     *
     */
    @Override
    @TaskAnnotation("save")
    public boolean save(SessionFactory factory, LinePatrolCheckSatellite linePatrolCheckSatellite) {
        LinePatrolCheckSatelliteMapper mapper = factory.getMapper(LinePatrolCheckSatelliteMapper.class);
        Assert.notNull(linePatrolCheckSatellite.getDataSource(), "数据来源不能为空");
        if (linePatrolCheckSatellite.getStatus() == null) {
            linePatrolCheckSatellite.setStatus("0");
        }
        if (linePatrolCheckSatellite.getCode() == null) {
            String prefix = "";
            if (satellite.equals(linePatrolCheckSatellite.getDataSource())) {
                prefix = "HSWX";
            } else if (monitorChange.equals(linePatrolCheckSatellite.getDataSource())) {
                prefix = "HSJC";
            } else if (uavRisk.equals(linePatrolCheckSatellite.getDataSource())) {
                prefix = "HSUAV";
            }
            String code = CodeTools.getCodeNo(prefix, 3);
            linePatrolCheckSatellite.setCode(code);
        }
        return mapper.insertOrUpdate(linePatrolCheckSatellite) > 0;
    }

    @Override
    @TaskAnnotation("saveVo")
    public boolean saveVo(SessionFactory factory, LinePatrolCheckSatelliteVO linePatrolCheckSatelliteVO) {
        save(factory, linePatrolCheckSatelliteVO);
        // 2. 保存人员信息
        List<LineStaff> checkStaffs = linePatrolCheckSatelliteVO.getCheckStaffs();
        checkStaffs.forEach(e -> {
            e.setOrderId(linePatrolCheckSatelliteVO.getId());
            e.setStaffType(staffType);
        });
        lineStaffService.removeByOrderId(factory, linePatrolCheckSatelliteVO.getId());
        lineStaffService.saveBatch(factory, checkStaffs);

        // 3. 关联巡视工单
        List<String> patrolIds = linePatrolCheckSatelliteVO.getPatrolIds();
        if (CollUtil.isEmpty(patrolIds)) {
            return true;
        }
        if (satellite.equals(linePatrolCheckSatelliteVO.getDataSource())) {
            return linePatrolSatelliteService.fillCheck(factory, linePatrolCheckSatelliteVO, patrolIds);
        } else if (monitorChange.equals(linePatrolCheckSatelliteVO.getDataSource())) {
            return linePatrolMonitorChangeService.fillCheck(factory, linePatrolCheckSatelliteVO, patrolIds);
        } else if (uavRisk.equals(linePatrolCheckSatelliteVO.getDataSource())) {
            return lineRiskPatrolUnvDetailService.fillCheck(factory, linePatrolCheckSatelliteVO, patrolIds);
        }
        return false;
    }

    /**
     * 修改数据
     *
     */
    @Override
    @TaskAnnotation("update")
    public boolean update(SessionFactory factory, LinePatrolCheckSatellite linePatrolCheckSatellite) {
        LinePatrolCheckSatelliteMapper mapper = factory.getMapper(LinePatrolCheckSatelliteMapper.class);
        return mapper.update(linePatrolCheckSatellite) > 0;
    }

    /**
     * 通过主键删除数据
     *
     */
    @Override
    @TaskAnnotation("deleteById")
    public boolean deleteById(SessionFactory factory, String id) {
        LinePatrolCheckSatellite linePatrolCheckSatellite = getById(factory, id);
        Assert.isTrue(!"1".equals(linePatrolCheckSatellite.getStatus()), "只有草稿状态才允许删除");
        // @TODO 删除后解除和巡视工单关联
        if (satellite.equals(linePatrolCheckSatellite.getDataSource())) {
            linePatrolSatelliteService.clearCheck(factory, id);
        } else if (monitorChange.equals(linePatrolCheckSatellite.getDataSource())) {
            linePatrolMonitorChangeService.clearCheck(factory, id);
        } else if (uavRisk.equals(linePatrolCheckSatellite.getDataSource())) {
            lineRiskPatrolUnvDetailService.clearCheck(factory, id);
        }
        LinePatrolCheckSatelliteMapper mapper = factory.getMapper(LinePatrolCheckSatelliteMapper.class);
        return mapper.hidden(id) > 0;
    }
}
